<?php

namespace App\Http\Controllers\Api;

use App\Http\Config\ErrorCode;
use App\Library\TcScfUtil;
use App\Library\UpTools;
use App\Models\Admin\Configs;
use App\Models\Admin\TcAuther;
use App\Models\Admin\TencentTransfer;
use App\Models\Orders;
use App\Models\WalletLogs;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;

class TencentController extends CommonController
{
    public function __construct()
    {
        parent::__construct();
    }

    // 查询订单
    public function selectOrder(Request $request){
        if ($this->returnData['status'] > 0){
            return response()->json($this->returnData);
        }
        $con = Configs::query()->where("mall_id", $request->mallData["id"])
            ->select("tencent_secretid", "tencent_secrekey")
            ->first();
        if (empty($con) || !$con->tencent_secretid || !$con->tencent_secrekey){
            return response()->json(ErrorCode::code("customized", "腾讯云参数未配置"));
        }
        $requestParams = [
            'Offset' => $request->page_no ? $request->page_no - 1 : 0, 'Limit' => intval($request->page_size ?: 10), "Order" => 0
        ];
        $requestParams["Offset"] = $requestParams["Offset"] * $requestParams["Limit"];
        if($request->status){
            $requestParams['Status'] = intval($request->status);
        }
        if($request->owner_uin){
            $requestParams['OwnerUins'][0] = $request->owner_uin;
        }
        if($request->deal_names){
            $requestParams['DealNames'][0] = $request->deal_names;
        }
        if($request->start_time){
            $requestParams['CreatTimeRangeStart'] = $request->start_time;
        }
        if($request->end_time){
            $requestParams['CreatTimeRangeEnd'] = $request->end_time;
        }
        if($request->pay_mode){
            $requestParams['PayerMode'] = intval($request->pay_mode);
        }
        $type = $request->type ?: 1;
        $res = TcScfUtil::getInstance($con->tencent_secretid, $con->tencent_secrekey, 'partner')->describeSalesmans(["Offset" => 0, "Limit" => 100000]);
        $salesData = !empty($res["data"]['AgentSalesmanSet']) ? $res["data"]['AgentSalesmanSet'] : [];
        if($type == "1") {
            $res = TcScfUtil::getInstance($con->tencent_secretid, $con->tencent_secrekey, 'partner')->describeAgentDealsCache($requestParams);
        }else{
            $res = TcScfUtil::getInstance($con->tencent_secretid, $con->tencent_secrekey, 'partner')->describeAgentPayDeals($requestParams);
        }
        if ($res['code'] == 0){
            $this->returnData['data'] = [
                "total" => $res['data']['TotalCount'], "count" => $res['data']['TotalCount'],
                "list" => UpTools::transferFields($type == "1" ? $res['data']['AgentDealSet'] : $res['data']['AgentPayDealSet'])
            ];
            $this->getOrder($this->returnData["data"], $request, $requestParams, $con, $type);
            foreach ($this->returnData["data"]["list"] as &$item){
                $item["salesName"] = '';
                foreach ($salesData as $t){
                    if($t["SalesUin"] == $item["salesUin"]) {
                        $item["salesName"] = $t["SalesName"];
                        break;
                    }
                }
            }
            $this->returnData['data'] = $this->returnData["data"]["list"];
        }else{
            $this->returnData['status'] = 1;
            $this->returnData['msg'] = isset($res['msg']) ? ($res['msg'] == 'CreatTimeRangeStart must be within 15 days' ? "搜索时间必须在15天内" : $res['msg']) : '请求失败';
        }
        return response()->json($this->returnData);
    }

    public function getOrder(&$data, $request, $requestParams, $con, $type = 1){
        if ($request->sales_uin) {
            $saleUin[] = $request->sales_uin;
        } else {
            if ($this->user["position"] != "超级管理员") {
                $tt = DB::table('permissions as p')
                    ->leftJoin('admin_permission_role as pr', 'pr.permission_id', '=', 'p.id')
                    ->leftJoin('admin_role_user as ru', 'ru.role_id', '=', 'pr.role_id')
                    ->where("ru.user_id", $this->user["id"])
                    ->where("p.name", "admin.tencent.checkAllOrder")
                    ->count();
                if ($tt) {
                    return true;
                }
            }else{
                return true;
            }
            $sdf = TcAuther::query()->where(["mall_id" => $request->mallData["id"], "admin_id" => $this->user['id']])->select("id")->with("sale_list")->first();
            if (!empty($sdf["sale_list"])) {
                $saleUin = array_column($sdf["sale_list"]->toArray(), "sales_uin");
            }
        }
        if (!empty($saleUin)) {
            global $num;
            $num = 0;
            $fun = function ($data, $totalLimit, $start) use ($saleUin) {
                global $num;
                $temp = [];
                foreach ((array)$data as $item) {
                    if (in_array($item["salesUin"], $saleUin) || (!$item["salesUin"] && in_array($this->defaultSale[0]["sales_uin"], $saleUin))) {
                        if ($totalLimit > $num && $start <= $num) {
                            $temp[] = $item;
                            $num++;
                        } else {
                            break;
                        }
                    }
                }
                return $temp;
            };
            $pageNo = $request->page_no ?: 1;
            if ($pageNo > 1) {
                $tempParam = $requestParams;
                $total = $tempParam["Limit"] * ($pageNo - 1);
                $tempData = [];
                for ($i = 1; $i <= ceil($total / 1000); $i++) {
                    $tempParam["Offset"] = ($i - 1) * 1000;
                    $tempParam["Limit"] = $total <= 1000 * $i ? $total - $tempParam["Offset"] : 1000;
                    if ($type === 1) {
                        $res = TcScfUtil::getInstance($con->tencent_secretid, $con->tencent_secrekey, 'partner')->describeAgentDealsCache($tempParam);
                        if (!empty($res['data']['AgentDealSet'])) {
                            $tempData = array_merge($tempData, UpTools::transferFields($res['data']['AgentDealSet']));
                        }
                    } else {
                        $res = TcScfUtil::getInstance($con->tencent_secretid, $con->tencent_secrekey, 'partner')->describeAgentPayDeals($tempParam);
                        if (!empty($res['data']['AgentPayDealSet'])) {
                            $tempData = array_merge($tempData, UpTools::transferFields($res['data']['AgentPayDealSet']));
                        }
                    }
                }
                $data["list"] = array_merge($tempData, $data["list"]);
                unset($tempData);
            }
            $totalLimit = $requestParams["Limit"];
            $data["list"] = $fun($data["list"], $totalLimit, $requestParams["Offset"]);
            $data["count"] = count($data["list"]);
            while ($totalLimit > $num) {
                if ($data["total"] <= $requestParams["Offset"]) {
                    break;
                }
                $requestParams["Offset"] = $requestParams["Offset"] + $requestParams["Limit"];
                $requestParams["Limit"] = 1000;
                if ($type === 1) {
                    $res = TcScfUtil::getInstance($con->tencent_secretid, $con->tencent_secrekey, 'partner')->describeAgentDealsCache($requestParams);
                    if (!empty($res['data']['AgentDealSet'])) {
                        $res = $fun(UpTools::transferFields($res['data']['AgentDealSet']), $totalLimit, 0);
                        $data["list"] = array_merge($data["list"], $res);
                        $data["count"] = count($data["list"]);
                    }
                } else {
                    $res = TcScfUtil::getInstance($con->tencent_secretid, $con->tencent_secrekey, 'partner')->describeAgentPayDeals($requestParams);
                    if (!empty($res['data']['AgentPayDealSet'])) {
                        $res = $fun(UpTools::transferFields($res['data']['AgentPayDealSet']), $totalLimit, 0);
                        $data["list"] = array_merge($data["list"], $res);
                        $data["count"] = count($data["list"]);
                    }
                }
            }
        } else {
            $data["count"] = 0;
            $data["list"] = [];
        }
    }

    // 代付订单
    public function payOrder(Request $request){
        if ($this->returnData['status'] > 0){
            return response()->json($this->returnData);
        }
        $con = Configs::query()->where("mall_id", $request->mallData["id"])
            ->select("tencent_secretid", "tencent_secrekey")
            ->first();
        if (empty($con) || !$con->tencent_secretid || !$con->tencent_secrekey){
            return response()->json(ErrorCode::code("customized", "腾讯云参数未配置"));
        }
        if(!$request->owner_uin || !$request->deal_name){
            return response()->json(ErrorCode::code("customized", "缺失参数"));
        }
        $listData = [$request->deal_name];
        $price = 0;
        // 查询关联单
        $res = TcScfUtil::getInstance($con->tencent_secretid, $con->tencent_secrekey, 'partner')->describeAgentPayDeals([
            "Offset" => 0, "Limit" => 100, "Order" => 0, "Status" => 1, "OwnerUins" => [$request->owner_uin]
        ]);
        if(!empty($res['data']['AgentPayDealSet'])) {
            $listData = [];
            $temp = array_column($res['data']['AgentPayDealSet'], "BigDealId", "DealName");
            foreach ($res['data']['AgentPayDealSet'] as $item) {
                if (isset($temp[$request->deal_name]) && $item["BigDealId"] == $temp[$request->deal_name]) {
                    $price += $item["GoodsPrice"]['RealTotalCost'] / 100;
                    $listData[] = $item["DealName"];
                }
            }
        }
        if($this->user["position"] != "超级管理员") {
            // 获取用户折扣信息
            $user_discount = TcAuther::query()->where('admin_id', $this->user["id"])->select('quota', 'old_quota', 'assign_quota')->first();
            $user_discount = json_decode(json_encode($user_discount), true);
            $res = TcScfUtil::getInstance($con->tencent_secretid, $con->tencent_secrekey, 'partner')->describeAgentAuditedClients([
                "ClientUin" => $request->owner_uin
            ]);
            $ClientType = !empty($res["data"]['AgentClientSet']) ? $res["data"]['AgentClientSet'][0]['ClientType'] : "";
            if ($ClientType == "new") {
                if ($price > $user_discount['quota']) {
                    return response()->json(ErrorCode::code("customized", "订单金额大于代付限额"));
                }
            } elseif ($ClientType == 'old') {
                if ($price > $user_discount['old_quota']) {
                    return response()->json(ErrorCode::code("customized", "订单金额大于代付限额"));
                }
            } elseif ($ClientType == 'assign') {
                if ($price > $user_discount['assign_quota']) {
                    return response()->json(ErrorCode::code("customized", "订单金额大于代付限额"));
                }
            } else {
                return response()->json(ErrorCode::code("customized", "客户类型错误"));
            }
        }
        DB::beginTransaction();
        try{
            //添加本地订单
            $order["order_sn"] = date("YmdHis") . rand(100, 999);
            $order["title"] = "腾讯云订单";
            $order["type"] = 1;
            $order["uid"] = $this->user['id'];
            $order["uname"] = $this->user['name'];
            $order["price"] = $price;  //单价
            $order["amount"] = $price ;
            $order["submitter"] = $this->user['name'];
            $order["total_price"] = $price;
            $order["discount"] = '';
            $order["long"] = 4;
            $order["pay_status"] = 2;
            $order["status"] = 1;
            $order["pay_type"] = 2;
            $order["owner_uin"] = $request->owner_uin;
            $order["pay_time"] = Carbon::now()->toDateTimeString();
            $order["created_at"] = Carbon::now()->toDateTimeString();
            $order["updated_at"] = Carbon::now()->toDateTimeString();
            Orders::query()->insertGetId($order);
            //添加消费记录
            $log["uid"] = $this->user['id'];
            $log["type"] = 9;
            $log["money"] = '-' . $price;
            $log["wallet"] = '小程序用户代付';
            $log["remarks"] = "腾讯云订单付款";
            $log["operation"] = "消费￥" . $price . ",订单号：" . $order["order_sn"];
            $log["created_at"] = Carbon::now()->toDateTimeString();
            $log["updated_at"] = Carbon::now()->toDateTimeString();
            WalletLogs::query()->insertGetId($log);
            $res = TcScfUtil::getInstance($con->tencent_secretid, $con->tencent_secrekey, 'partner')->agentPayDeals([
                "OwnerUin" => $request->owner_uin, "DealNames" => $listData, "AgentPay" => 1,//1：代付  0：自付
            ]);
            if($res["code"] != 0){
                if(strpos($res["msg"], "DealNames is null or empty") !== false){
                    DB::rollback();
                    $this->returnData["msg"] = "此订单状态正在更新，请稍后";
                }else {
                    throw new \Exception($res["msg"]);
                }
            }
            DB::commit();
            $this->returnData['msg'] = '支付成功';
            return response()->json($this->returnData);
        } catch(\Exception $e){
            DB::rollback();
            return response()->json(ErrorCode::code("customized", $e->getMessage()));
        }
    }

    // 我的客户
    public function searchCustomerList(Request $request){
        if ($this->returnData['status'] > 0){
            return response()->json($this->returnData);
        }
        $con = Configs::query()->where("mall_id", $request->mallData["id"])
            ->select("tencent_secretid", "tencent_secrekey")
            ->first();
        if (empty($con) || !$con->tencent_secretid || !$con->tencent_secrekey){
            return response()->json(ErrorCode::code("customized", "腾讯云参数未配置"));
        }
        $requestParams = ["OrderDirection" => "DESC", 'Offset' => $request->page_no ? $request->page_no - 1 : 0, "Limit" => $request->page_size ?: 10];
        $requestParams["Offset"] = $requestParams["Offset"] * $requestParams["Limit"];
        if ($request->client_uin){
            $requestParams['ClientUin'] = $request->client_uin;
        }
        if ($request->client_name){
            $requestParams['ClientName'] = $request->client_name;
        }
        if ($request->client_type){
            $requestParams['ClientType'] = $request->client_type;
        }
        if ($request->sales_name){
            $requestParams['SalesName'] = $request->sales_name;
        }
        if (!empty($request->sales_uin)){
            $requestParams['SalesUin'] = strval($request->sales_uin);
        }
        $type = $request->type ?: 1;
        if($type == 1) {
            $res = TcScfUtil::getInstance($con->tencent_secretid, $con->tencent_secrekey, "partner")->describeAgentAuditedClients($requestParams);
        }else{
            $res = TcScfUtil::getInstance($con->tencent_secretid, $con->tencent_secrekey, "partner")->describeAgentClients($requestParams);
        }
        if($res["code"] != 0){
            return response()->json(ErrorCode::code("customized", $res["msg"]));
        }
        $this->returnData["data"] = UpTools::transferFields($res["data"]["AgentClientSet"]);
        foreach ($this->returnData["data"] as &$item){
            if($type == 1) {
                $item["agentTime"] = date("Y-m-d H:i", $item["agentTime"]);
            }else {
                $item["applyTime"] = date("Y-m-d H:i", $item["applyTime"]);
            }
        }
        unset($item);
        return response()->json($this->returnData);
    }

    // 审核客户
    public function auditCustomer(Request $request){
        if ($this->returnData['status'] > 0){
            return response()->json($this->returnData);
        }
        $text = $request->type ?: "accept";
        $con = Configs::query()->where("mall_id", $request->mallData["id"])
            ->select("tencent_secretid", "tencent_secrekey")
            ->first();
        if (empty($con) || !$con->tencent_secretid || !$con->tencent_secrekey){
            return response()->json(ErrorCode::code("customized", "腾讯云参数未配置"));
        }
        $requestParams = ["ClientUin" => $request->client_uin ?: "", "AuditResult" => $text, "Note" => $request->note ?: ""];
        $res = TcScfUtil::getInstance($con->tencent_secretid, $con->tencent_secrekey, "partner")->auditApplyClient($requestParams);
        if($res["code"] != 0){
            return response()->json(ErrorCode::code("customized", $res["msg"]));
        }
        $this->returnData['msg'] = '审核成功';
        return response()->json($this->returnData);
    }

    // 转账
    public function getCustomerTransferMoney(Request $request){
        if ($this->returnData['status'] > 0){
            return response()->json($this->returnData);
        }
        if (!$request->client_uin){
            return response()->json(ErrorCode::code("params_not_exist", "	客户账号ID"));
        }
        if (!$request->amount){
            return response()->json(ErrorCode::code("params_not_exist", "	转账金额"));
        }
        try {
            if(Cache::has("{$request->mallData["id"]}_{$this->user["id"]}_tc_transfer")) {
                return response()->json($this->returnData);
            }
            Cache::put("{$request->mallData["id"]}_{$this->user["id"]}_tc_transfer", 1, 1);
            $con = Configs::query()->where("mall_id", $request->mallData["id"])
                ->select("tencent_secretid", "tencent_secrekey")
                ->first();
            if (empty($con) || !$con->tencent_secretid || !$con->tencent_secrekey){
                return response()->json(ErrorCode::code("customized", "腾讯云参数未配置"));
            }
            if($this->user["position"] != "超级管理员") {
                $transfer_quota = TcAuther::query()->where(["admin_id" => $this->user["id"]])->value("transfer_quota");
                $transfer_quota = $transfer_quota ?: 0;
                $total = TencentTransfer::query()->where(["user_id" => $this->user["id"]])->sum("money");
                if($total + $request->amount > $transfer_quota){
                    return response()->json(ErrorCode::code("customized", "已超过可转账限额了"));
                }
            }
            $requestParams = ["ClientUin" => $request->client_uin, 'Amount' => $request->amount * 100];
            $this->returnData = TcScfUtil::getInstance($con->tencent_secretid, $con->tencent_secrekey, "partner")->agentTransferMoney($requestParams);
            $this->returnData["status"] = $this->returnData["code"];
            if($this->returnData["code"] == '0'){
                try {
                    TencentTransfer::query()->insert([
                        "mall_id" => $request->mallData["id"], "user_id" => $this->user["id"], "customer" => $requestParams["ClientUin"],
                        "money" => $request->amount, "create_time" => Carbon::now()->toDateTimeString()
                    ]);
                    Cache::forget("{$request->mallData["id"]}_{$this->user["id"]}_tc_transfer");
                }catch (\Exception $e){
                    $this->returnData["msg"] = "转账成功，但后续操作失败";
                }
            }else{
                if(strpos($this->returnData["msg"], "call interface error") !== false){
                    $this->returnData["msg"] = "余额不够";
                }
            }
        }catch (\Exception $e){
            $this->returnData = ErrorCode::code("customized", $e->getMessage());
        }
        unset($this->returnData["code"]);
        return response()->json($this->returnData);
    }

    public $defaultSale = [
        ["sales_name" => "未指派", "sales_uin" => "0000", "uin" => "0000"],
        ["SalesName" => "未指派", "SalesUin" => "0000", "Uin" => "0000"]
    ];

    public function getSaleByUser(Request $request){
        if ($this->returnData['status'] > 0){
            return response()->json($this->returnData);
        }
        $fun = function (){
            $con = Configs::query()->where("mall_id", request()->mallData["id"])
                ->select("tencent_secretid", "tencent_secrekey")
                ->first();
            if (empty($con) || !$con->tencent_secretid || !$con->tencent_secrekey){
                throw new \Exception("腾讯云参数未配置");
            }
            $params = [
                "OrderDirection" => "DESC", "Offset" => 0, "Limit" => 1000
            ];
            $res = TcScfUtil::getInstance($con->tencent_secretid, $con->tencent_secrekey, 'partner')->describeSalesmans($params);
            $data = [];
            if(!empty($res["data"])){
                foreach ($res['data']['AgentSalesmanSet'] as $item){
                    $data[] = ["sales_name" => $item["SalesName"], "sales_uin" => $item["SalesUin"]];
                }
            }
            $data[] = $this->defaultSale[0];
            return $data;
        };
        if($this->user["position"] == "超级管理员") {
            $this->returnData["data"] = $fun();
            return $this->returnData;
        }else{
            $tt = DB::table('permissions as p')
                ->leftJoin('admin_permission_role as pr', 'pr.permission_id', '=', 'p.id')
                ->leftJoin('admin_role_user as ru', 'ru.role_id', '=', 'pr.role_id')
                ->where("ru.user_id", $this->user["id"])
                ->where("p.name", "admin.tencent.checkAllCustomer")
                ->count();
            if ($tt) {
                $this->returnData["data"] = $fun();
                return $this->returnData;
            }
        }
        $sdf = TcAuther::query()->where(["mall_id" => $request->mallData["id"], "admin_id" => $this->user["id"]])->select("id")->with("sale_list")->first();
        if(!empty($sdf["sale_list"])) {
            $this->returnData["data"] = $sdf["sale_list"];
        }else{
            $this->returnData["data"] = [];
        }
        return $this->returnData;
    }

    public function getCustomerInfo(Request $request){
        if ($this->returnData['status'] > 0){
            return response()->json($this->returnData);
        }
        if(!$request->client_uin){
            return ErrorCode::code("params_not_exist", "客户ID");
        }
        $con = Configs::query()->where("mall_id", $request->mallData["id"])
            ->select("tencent_secretid", "tencent_secrekey")
            ->first();
        if (empty($con) || !$con->tencent_secretid || !$con->tencent_secrekey){
            return response()->json(ErrorCode::code("customized", "腾讯云参数未配置"));
        }
        $client = TcScfUtil::getInstance($con->tencent_secretid, $con->tencent_secrekey, "partner");
        $result = $client->describeClientBalance(['ClientUin' => $request->client_uin]);
        $this->returnData['data'] = ['balance' => isset($result['data']['Balance']) ? $result['data']['Balance'] / 100 : 0];
        $result = $client->describeAgentClientGrade($request->client_uin);
        $this->returnData['data'] = array_merge($this->returnData['data'], ['grade' => !empty($result['data']['ClientGrade']) ? $result['data']['ClientGrade'] : '-']);
        return $this->returnData;
    }
}
